﻿
Imports Odyssee.WebControles
Imports OpenDelib.ServiceDeliberations

Public MustInherit Class FicheDossierPage
    Inherits FichePage(Of String, ServiceDossiers.Dossier, ServiceDossiers.DossiersClient, ServiceDossiers.CriteresRechercheDossier)

    Protected ReadOnly Property TypeDossier As String
        Get
            Return Tools.GetInstance().Parametre(TypeParametre.TypeDossier, Me.TypeDelib)
        End Get
    End Property
    Protected ReadOnly Property AssistantCreationDossier As String
        Get
            Return Tools.GetInstance().Parametre(TypeParametre.AssistantCreationDossier, Me.TypeDelib)
        End Get
    End Property
    Public ReadOnly Property ListeEtats As ServiceParametre.OIItemListResult
        Get
            If (ViewState("liste_etats") Is Nothing) Then
                ' Chargement de la liste des états de dossier associés au type de dossier
                Using svc As New ServiceParametre.ParametresClient
                    Dim params As New ServiceParametre.ListeParametreParameters
                    params.Authentication = New ServiceParametre.AuthenticationParameters
                    params.Authentication.Token = Tools.GetInstance.getToken
                    params.EntiteParametrage = 25
                    params.Param1 = Me.TypeDossier

                    Try
                        ViewState("liste_etats") = svc.ListeParametre(params)
                    Catch ex As Exception
                        ViewState("liste_etats") = Nothing
                        NotifyErreur(ex.Message)
                    End Try
                End Using
            End If
            Return CType(ViewState("liste_etats"), ServiceParametre.OIItemListResult)
        End Get
    End Property
    Public Property ListeAssistants As ServiceAssistant.OIItemListResult
        Get
            Return CType(ViewState("liste_assistants"), ServiceAssistant.OIItemListResult)
        End Get
        Private Set(value As ServiceAssistant.OIItemListResult)
            ViewState("liste_assistants") = value
        End Set
    End Property

    Protected MustOverride ReadOnly Property TypeDelib As TypeDeliberation
    Protected MustOverride ReadOnly Property UtiliseDocuments As Boolean
    Protected MustOverride ReadOnly Property SeparateurTraitements As ToolBarSeparator
    Protected MustOverride ReadOnly Property BoutonTraitements As ToolBarTextImageMenuButton


    Private Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        ' Permet de récupérer le fichier qui viens d'être drag & drop
        If Me.UtiliseDocuments AndAlso Request.Files.Count = 1 Then
            'Copie du fichier déposé dans la dropzone sur le serveur
            Dim fichier As HttpPostedFile = Request.Files(0)

            Dim cheminFichier As String = Request.PhysicalApplicationPath & "Temp\" & Tools.GetInstance.getToken
            If Not IO.Directory.Exists(cheminFichier) Then IO.Directory.CreateDirectory(cheminFichier)

            cheminFichier &= "\" & System.IO.Path.GetFileName(fichier.FileName)

            Dim filestream As IO.FileStream = IO.File.Create(cheminFichier)
            Dim file As IO.Stream = fichier.InputStream
            file.Seek(0, IO.SeekOrigin.Begin)
            file.CopyTo(filestream)
            filestream.Dispose()
        End If

        InitialiserBoutonsTraitement()
    End Sub

    Private Sub btnAssistant_Click(sender As Object, e As EventArgs)
        Dim codeAss As String

        codeAss = CType(sender, Odyssee.WebControles.ToolBarButton).CommandArgument

        Using svc As New ServiceAssistant.AssistantsClient
            Dim params As New ServiceAssistant.AssistantParameters
            params.Authentication = New ServiceAssistant.AuthenticationParameters
            params.Authentication.Token = Tools.GetInstance.getToken
            params.CleEntite = CleEntite
            params.CodeAssistant = codeAss

            Try
                Dim results As ServiceAssistant.OperationResult
                results = svc.LancerAssistant(params)
                If results.OK Then
                    NotifySuccess("Opération effectuée avec succès.")
                    InitialiserEntite()
                    InitialiserPage()
                Else
                    NotifyErreur(results.ErrorMessage)
                End If
            Catch ex As Exception
                NotifyErreur(ex.Message)
            End Try
        End Using
    End Sub



    Protected Overrides Function InitialiserCriteresRechercheEntite(cle As String) As ServiceDossiers.CriteresRechercheDossier
        Dim criteres As New ServiceDossiers.CriteresRechercheDossier
        criteres.Authentication = New ServiceDossiers.AuthenticationParameters
        criteres.Authentication.Token = Tools.GetInstance.getToken
        criteres.Code = cle
        Return criteres
    End Function
    Protected Overrides Function RechercherEntite(svc As ServiceDossiers.DossiersClient, criteres As ServiceDossiers.CriteresRechercheDossier, ByRef ok As Boolean, ByRef messageErreur As String) As List(Of ServiceDossiers.Dossier)
        Dim results As ServiceDossiers.ResultatRechercheDossier
        results = svc.Recherche(criteres)
        If results Is Nothing Then Return Nothing
        ok = results.OK
        messageErreur = results.ErrorMessage
        Return results.Dossiers
    End Function
    Protected Overrides Sub InitialiserObjetEntite(entite As ServiceDossiers.Dossier)
        If entite.ZoneSup Is Nothing Then entite.ZoneSup = New ServiceDossiers.ZoneSup
    End Sub

    Protected Overrides Sub InitialiserParametres()
        MyBase.InitialiserParametres()

        If ModeFiche = Tools.ModeFiche.Modification Then
            ' Chargement de la liste des assistants associés au type de dossier
            Using svc As New ServiceAssistant.AssistantsClient
                Dim params As New ServiceAssistant.ListeDeclencheursAssistantParameters
                params.Authentication = New ServiceAssistant.AuthenticationParameters
                params.Authentication.Token = Tools.GetInstance.getToken
                params.TypeAssistant = 6
                params.TypeDeclencheur = 4
                params.TypeEvenement = 99
                params.CodeParametre = Me.TypeDossier
                params.CodeParametre2 = ""

                Try
                    Me.ListeAssistants = svc.ListeAssistantsSelonParametreEtDeclencheur(params)
                    If Me.ListeAssistants Is Nothing OrElse Not Me.ListeAssistants.OK Then
                        Me.ListeAssistants = Nothing
                        NotifyErreur("Impossible de charger les assistants associés au type de dossier '" & Me.TypeDossier & "'" & If(Me.ListeAssistants IsNot Nothing, " :" & ControlChars.NewLine & Me.ListeAssistants.ErrorMessage, "."))
                    End If
                Catch ex As Exception
                    Me.ListeAssistants = Nothing
                    NotifyErreur(ex.Message)
                End Try
            End Using

        End If
    End Sub

    Protected Overridable Sub InitialiserBoutonsTraitement()
        ' Ajout d'un bouton pour chaque assistant dans la barre d'outils
        Me.SeparateurTraitements.Visible = Me.ListeAssistants IsNot Nothing AndAlso Me.ListeAssistants.Liste.Count > 0
        Me.BoutonTraitements.Visible = Me.ListeAssistants IsNot Nothing AndAlso Me.ListeAssistants.Liste.Count > 0
        If Me.ListeAssistants IsNot Nothing AndAlso Me.ListeAssistants.Liste.Count > 0 Then
            For Each item As ServiceAssistant.OIItem In Me.ListeAssistants.Liste
                Dim btnAss As New Odyssee.WebControles.ToolBarButton()
                btnAss.CommandArgument = item.Code
                btnAss.ID = "btnAss" & item.Code
                btnAss.OnClientClick = "return confirm('Êtes-vous sûr de vouloir exécuter cette action ?');"
                btnAss.Text = item.Libelle
                AddHandler btnAss.Click, AddressOf btnAssistant_Click
                Me.BoutonTraitements.Add(btnAss)
            Next
        End If
    End Sub

    Protected Overrides Sub InitialiserPage()
        MyBase.InitialiserPage()

        Select Case Me.ModeFiche

            Case Tools.ModeFiche.Creation
                Me.SeparateurTraitements.Visible = False
                Me.BoutonTraitements.Visible = False

            Case Tools.ModeFiche.Modification


        End Select
    End Sub


    Protected Sub InitialiserPiecesJointes(gv As GridView)
        Using svc As New ServiceDocuments.DocumentsClient
            Dim params As New ServiceDocuments.CriteresRechercheDocument
            params.Authentication = New ServiceDocuments.AuthenticationParameters
            params.Authentication.Token = Tools.GetInstance.getToken
            params.DossierLie = Me.CleEntite

            Dim results As ServiceDocuments.ResultatRechercheDocument = Nothing
            Try
                results = svc.Recherche(params)
                If results Is Nothing OrElse Not results.OK Then
                    NotifyErreur("Impossible de charger les pièces jointes d" & If(Me.LibelleApostrophe, "e l'", If(Me.LibelleFeminin, "e la ", "u ")) & Me.LibelleEntite & " '" & Me.CleEntite & "'" & If(results Is Nothing, ".", " :" & ControlChars.NewLine & results.ErrorMessage))
                Else
                    gv.DataSource = results.Documents
                    gv.DataBind()
                End If
            Catch ex As Exception
                NotifyErreur(ex.Message)
            End Try
        End Using
    End Sub
    Protected Sub AjouterPieceJointe(cleDocument As Integer, gv As GridView)
        Using svc As New ServiceDossiers.DossiersClient
            Dim params As New ServiceDossiers.ParametresLienDossierDocument
            params.Authentication = New ServiceDossiers.AuthenticationParameters
            params.Authentication.Token = Tools.GetInstance.getToken
            params.CleDocument = cleDocument
            params.CodeDossier = CleEntite

            Try
                Dim results As ServiceDossiers.OperationResult
                results = svc.AjouterLienDocument(params)
                If results.OK Then
                    NotifySuccess("Ajout effectué avec succès.")
                    InitialiserPiecesJointes(gv)
                Else
                    NotifyErreur(results.ErrorMessage)
                End If
            Catch ex As Exception
                NotifyErreur(ex.Message)
            End Try
        End Using
    End Sub
    Protected Sub SupprimerPieceJointe(cleDocument As Integer, gv As GridView)
        Using svc As New ServiceDossiers.DossiersClient
            Dim params As New ServiceDossiers.ParametresLienDossierDocument
            params.Authentication = New ServiceDossiers.AuthenticationParameters
            params.Authentication.Token = Tools.GetInstance.getToken
            params.CleDocument = cleDocument
            params.CodeDossier = CleEntite

            Try
                Dim results As ServiceDossiers.OperationResult
                results = svc.SupprimerLienDocument(params)
                If results.OK Then
                    NotifySuccess("Suppression effectuée avec succès.")
                    InitialiserPiecesJointes(gv)
                Else
                    NotifyErreur(results.ErrorMessage)
                End If
            Catch ex As Exception
                NotifyErreur(ex.Message)
            End Try
        End Using
    End Sub


    Protected Overrides Function Renseigner() As Boolean
        Me.Entite.Type = Me.TypeDossier
        Return True
    End Function
    Protected Overrides Function Creer() As Boolean
        Dim codeDossier As String = ""

        Me.Entite.DossierClos = False

        ' Création du dossier
        Using svc As New ServiceAssistant.AssistantsClient
            Dim params As New ServiceAssistant.AssistantParameters
            params.Authentication = New ServiceAssistant.AuthenticationParameters
            params.Authentication.Token = Tools.GetInstance.getToken
            params.CodeAssistant = Me.AssistantCreationDossier
            params.DefinitionDossier = Tools.Convert(Me.Entite)

            Try
                Dim results As ServiceAssistant.ExecutionAssistantResult = svc.LancerAssistant(params)
                If results Is Nothing OrElse Not results.OK Then
                    NotifyErreur("Impossible de créer l" & If(Me.LibelleApostrophe, "'", If(Me.LibelleFeminin, "a ", "e ")) & Me.LibelleEntite & If(results Is Nothing, ".", " :" & ControlChars.NewLine & results.ErrorMessage))
                    Return False
                Else
                    codeDossier = CStr(results.CleEntite)
                End If
            Catch ex As Exception
                NotifyErreur(ex.Message)
                Return False
            End Try
        End Using

        Me.Entite.Code = codeDossier
        Me.CleEntite = codeDossier

        Return True
    End Function
    Protected Overrides Function MettreAJour() As Boolean
        Using svc As New ServiceDossiers.DossiersClient
            ' Mise à jour du dossier
            Dim params As New ServiceDossiers.ParametresCreationDossier
            params.Authentication = New ServiceDossiers.AuthenticationParameters
            params.Authentication.Token = Tools.GetInstance.getToken
            params.Dossier = Entite

            Dim result As New ServiceDossiers.OperationResult
            Try
                result = svc.MiseAJour(params)
                If result.OK Then
                    NotifySuccess(Me.LibelleEntite.Substring(0, 1).ToUpper & Me.LibelleEntite.Substring(1) & " mis" & If(Me.LibelleFeminin, "e", "") & " à jour avec succès.")
                Else
                    NotifyErreur("Echec de la mise à jour d" & If(Me.LibelleApostrophe, "e l'", If(Me.LibelleFeminin, "e la ", "u ")) & Me.LibelleEntite & " : " & result.ErrorMessage)
                    Return False
                End If
            Catch ex As Exception
                NotifyErreur(ex.Message)
                Return False
            End Try
        End Using

        Return True
    End Function

End Class
